' Read and write hardware USART using Peek and Poke
'  For 16C63, 65(A), 73(A), 74(A)

' Define the USART registers
Symbol  PIR1 =  $0C             ' Peripheral Interrupt Flag register
Symbol  RCSTA = $18             ' Receive Status and Control register
Symbol  TXREG = $19             ' Transmit Data register
Symbol  RCREG = $1A             ' Receive Data register
Symbol  TRISC = $87             ' PortC Data Direction register
Symbol  TXSTA = $98             ' Transmit Status and Control register
Symbol  SPBRG = $99             ' Baud Rate Generator register


' Initialize USART
        Poke TRISC,%10111111    ' Set TX (PortC.6) to out, rest in
        Poke SPBRG,25           ' Set baud rate to 2400
        Poke RCSTA,%10010000    ' Enable serial port and continuous receive
        Poke TXSTA,%00100000    ' Enable transmit and asynchronous mode


' Echo received characters in infinite loop
loop:   Gosub charin            ' Get a character from serial input, if any
        If B1 = 0 Then loop     ' No character yet

        Gosub charout           ' Send character to serial output
        Goto loop               ' Do it forever


' Subroutine to get a character from USART receiver
charin: B1 = 0                  ' Preset to no character received

        Peek PIR1,B0            ' Get Flag register to B0
        If Bit5 = 0 Then ciret  ' If no receive flag then exit

        Peek RCREG,B1           ' Else get received character to B1

ciret:  Return                  ' Go back to caller


' Subroutine to send a character to USART transmitter
charout: Peek PIR1,B0           ' Get flag register to B0
        If Bit4 = 0 Then charout        ' Wait for transmit register empty

        Poke TXREG,B1           ' Send character to transmit register

        Return                  ' Go back to caller
